package com.lh.web.ctrl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lh.biz.IOpenUserBiz;
import com.lh.biz.IUserBiz;
import com.lh.biz.dto.in.openuser.BindUserInDto;
import com.lh.biz.dto.out.openuser.BindUserOutDto;
import com.lh.ctrl.BaseCtrl;
import com.lh.entity.Cart;
import com.lh.entity.OpenUser.OpenUserType;
import com.lh.exception.BizException;
import com.lh.oauth.OAuth;
import com.lh.oauth.OAuthFactory;

/**
 * @author liuhui
 * @version 1.0
 * @date 2013-4-29 下午4:43:12
 */
@Controller
@RequestMapping("open-user")
public class OpenUserCtrl extends BaseCtrl {
	
	@Resource
	private OAuthFactory oAuthFactory;
	
	@Resource
	private IOpenUserBiz openUserBiz;
	
	@RequestMapping("login")
	public String login(Integer type  ) throws BizException{
		OpenUserType openUserType = OpenUserType.get(type);
		OAuth oa = oAuthFactory.getOAuth(openUserType);
		if(oa == null ){
			throw new BizException(getMessage("unknow openUserType : ", type));
		}
		return "redirect:" + oa.genLoginUrl();
	}
	
	@RequestMapping("oauth-callback/{type}")
	public String oauthCallback(@PathVariable Integer type ,HttpServletRequest request , HttpServletResponse response) throws BizException{
		OAuth oa = null;
		OpenUserType openUserType = OpenUserType.get(type);
		oa = oAuthFactory.getOAuth(openUserType);
		if(oa == null ){
			throw new BizException(getMessage("unknow openUserType : ", type));
		}
		BindUserInDto inDto = new BindUserInDto();
		String cartId = getCookieValue(request.getCookies(), Cart.CART_COOKIE_NAME);
		if(StringUtils.isNotBlank(cartId)){
			inDto.setCartId(Long.parseLong(cartId));
		}
		inDto.setType(type);
		inDto.setCode(request.getParameter("code"));
		inDto.setRemoteAddress(request.getRemoteAddr());
		BindUserOutDto outDto  = openUserBiz.bindUser(inDto);
		addCookie(response, IUserBiz.SESSION_TOKEN_NAME, outDto.getSessionToken(), -1 );
		return "open-user/oauth-callback";
	}
}
